package org.cuatrovientos.erp.dao;
/**
 * 
 */


import java.util.List;

import org.cuatrovientos.erp.model.Message;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
/**
 * @author eneko_lana
 *
 */

/**
 * implementation of MessageDAOInterface
 * @author VB
 *
 */
public class MessageDAO implements MessageDAOInterface {

	@Autowired
	 private SessionFactory sessionFactory;
	

	/**
	 * default constructor
	 */
	public MessageDAO () {
		
	}
	
	/**
	 * returns Hibernate session
	 * @return
	 */
	 private Session getSession () {
		 return sessionFactory.getCurrentSession();
	 }
	
	/* 
	 * selects one Message by Id
	 * @param id
	 * @return Message
	 */
	 @Transactional(readOnly = true)
	public Message selectById(int id) {
		 Message Message = (Message) getSession().get(Message.class, id);
	    return Message;
	}

	/*
	 * retrieves all Messages from db
	 * @return List of Messages
	 */
	 @Transactional(readOnly = true)
	 public List<Message> selectAll() {
	 
	    List<Message> Messages = getSession().createQuery("from message").list();
	    return Messages;
	}
	
	/*
	 * retrieves all Messages from db
	 * @return List of Messages
	 */
	 @Transactional(readOnly = true)
	public int selectAllCount() {
	    List<Message> Messages = getSession().createQuery("from message").list();
	    return Messages.size();
	}

	/*
	 * inserts a new Message in database
	 * retrieves generated id and sets to Message instance
	 * @param new product
	 */
	 @Transactional
	public void insert(Message Message) {
	    Integer id = (Integer) getSession().save(Message);
	    Message.setId(id);           
	}

	/*
	 * updates Message
	 * @param Message to update
	 */
	 @Transactional
	public void update(Message Message) {
		getSession().merge(Message);
	}

	/*
	 * delete given Message
	 * @param Message to delete
	 */
	 @Transactional
	public void delete(Message Message) {
		getSession().delete(Message);
	}

	 @Transactional
	public void saveOrUpdate(Message Message) {

		getSession().saveOrUpdate(Message);
		
	}

	 /**
	  * deletes using id
	  */
	 @Transactional
	public void deleteById(int id) {
		 Message Message = (Message) getSession().load(Message.class,id);
		 getSession().delete(Message);
	}

	 /**
	  * performs search operation
	  */
	 @Transactional(readOnly = true)
	public List<Message> search(String title) {
		   Query query = getSession().createQuery("from message s where s.title like :title");
           query.setParameter("title", "%"+title+"%");
           
           List<Message> descriptions = query.list();
		
           return descriptions;
	}

}
